import {JSEncrypt} from 'jsencrypt';

const padWithLeadingZeros = (str: string): string => {
  return new Array(5 - str.length).join('0') + str;
};

const unicodeCharEscape = (charCode: number): string => {
  return '\\u' + padWithLeadingZeros(charCode.toString(16));
};

const unicodeEscape = (str: string): string => {
  return str
    .split('')
    .map((char: string): string => {
      const charCode = char.charCodeAt(0);
      return charCode > 127 ? unicodeCharEscape(charCode) : char;
    })
    .join('');
};

export default class RSA {
  public static rsaEncrypt(text: string, publicKey: string): string {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    const matchResult = unicodeEscape(text).match(/.{117}|.+$/g);
    if (matchResult) {
      return matchResult.map(sub => encrypt.encrypt(sub)).join('');
    }
    return '';
  }
}
